<template>
  <div class="inventory-count-page">
    <el-container>
      <el-header height="auto">
        <!-- 查询条件 -->
        <el-card shadow="never">
          <el-form
            :inline="true"
            :model="formInline"
            label-width="auto"
            class="filter-form"
          >
            <el-form-item label="盘点单号">
              <el-input
                v-model="formInline.inventoryCountCode"
                clearable
                placeholder="请输入"
                style="width: 180px"
              />
            </el-form-item>
            <el-form-item label="盘点结果">
              <el-select
                v-model="formInline.countResult"
                placeholder="请选择"
                clearable
                style="width: 160px"
              >
                <el-option label="草稿" :value="0" />
                <el-option label="有盈亏" :value="1" />
                <el-option label="无盈亏" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="盘点类型">
              <el-select
                v-model="formInline.countTypeId"
                placeholder="请选择"
                clearable
                style="width: 160px"
              >
                <el-option
                  v-for="item in countTypeOptions"
                  :key="item.countTypeId"
                  :label="item.countTypeName"
                  :value="item.countTypeId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="仓库名称">
              <el-select
                v-model="formInline.warehouseId"
                placeholder="请选择"
                clearable
                style="width: 180px"
                filterable
              >
                <el-option
                  v-for="item in warehouseOptions"
                  :key="item.warehouseId"
                  :label="item.warehouseName"
                  :value="item.warehouseId"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-space>
                <el-button type="primary" @click="handleQuery">查询</el-button>
                <el-button @click="handleReset">重置</el-button>
                <el-button @click="handleAdvancedSearch">高级搜索</el-button>
              </el-space>
            </el-form-item>
          </el-form>
        </el-card>
      </el-header>

      <el-main>
        <el-card shadow="never">
          <div class="toolbar">
            <el-space wrap>
              <el-button type="success" size="small" @click="handleCreate">
                新增
              </el-button>
              <el-button size="small" @click="handleBatchDelete">删除</el-button>
              <el-button size="small" @click="handleExport">导出</el-button>
              <el-button size="small" @click="handleVoid">作废</el-button>
              <el-button size="small" @click="handleLockWarehouse">
                锁定仓库
              </el-button>
              <el-button size="small" @click="handleRefresh">刷新</el-button>
            </el-space>
          </div>
          <!-- 盘点列表 -->
          <el-table
            ref="multipleTableRef"
            v-loading="loading"
            :data="tableData"
            row-key="inventoryCountId"
            border
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" />
            <el-table-column type="index" label="序号" width="70" />

            <el-table-column
              prop="inventoryCountCode"
              label="盘点单号"
              min-width="140"
            >
              <template #default="scope">
                <a
                  style="color: #67c23a; cursor: pointer"
                  @click="handleDetail(scope.row)"
                >
                  {{ scope.row.inventoryCountCode }}
                </a>
              </template>
            </el-table-column>
            <el-table-column
              prop="countResult"
              label="盘点结果"
              min-width="100"
            >
              <template #default="scope">
                <el-tag
                  :type="getResultTagType(scope.row.countResult)"
                  size="small"
                >
                  {{ getResultText(scope.row.countResult) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="warehouseName"
              label="仓库名称"
              min-width="120"
            />
            <el-table-column
              prop="countTypeName"
              label="盘点类型"
              min-width="120"
            />
            <el-table-column
              prop="countStartTime"
              label="盘点开始时间"
              min-width="140"
            >
              <template #default="scope">
                {{ formatDate(scope.row.countStartTime) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="countEndTime"
              label="盘点结束时间"
              min-width="140"
            >
              <template #default="scope">
                {{ formatDate(scope.row.countEndTime) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="outboundStatus"
              label="出库状态"
              min-width="100"
            >
              <template #default="scope">
                {{ getOutboundStatusText(scope.row.outboundStatus) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="inboundStatus"
              label="入库状态"
              min-width="100"
            >
              <template #default="scope">
                {{ getInboundStatusText(scope.row.inboundStatus) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="productNames"
              label="盘点货品"
              min-width="200"
              show-overflow-tooltip
            >
              <template #default="scope">
                <span :title="scope.row.productNames">
                  {{ scope.row.productNames || '-' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="countQuantity"
              label="盘点数量"
              min-width="100"
              align="right"
            />
            <el-table-column
              prop="gainQuantity"
              label="盘盈数量"
              min-width="100"
              align="right"
            >
              <template #default="scope">
                <span style="color: #67c23a">
                  {{ scope.row.gainQuantity || 0 }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="lossQuantity"
              label="盘亏数量"
              min-width="100"
              align="right"
            >
              <template #default="scope">
                <span style="color: #f56c6c">
                  {{ scope.row.lossQuantity || 0 }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="gainAmount"
              label="盘盈金额"
              min-width="120"
              align="right"
            >
              <template #default="scope">
                <span style="color: #67c23a">
                  ¥{{ Number(scope.row.gainAmount ?? 0).toFixed(2) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="lossAmount"
              label="盘亏金额"
              min-width="120"
              align="right"
            >
              <template #default="scope">
                <span style="color: #f56c6c">
                  ¥{{ Number(scope.row.lossAmount ?? 0).toFixed(2) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="handlerName"
              label="经办人"
              min-width="120"
              show-overflow-tooltip
            >
              <template #default="scope">
                {{ scope.row.handlerName || '-' }}
              </template>
            </el-table-column>
            <el-table-column
              prop="documentCreator"
              label="制单人"
              min-width="120"
              show-overflow-tooltip
            >
              <template #default="scope">
                {{ scope.row.documentCreator || '-' }}
              </template>
            </el-table-column>
            <el-table-column
              prop="organizationName"
              label="所在部门"
              min-width="140"
              show-overflow-tooltip
            >
              <template #default="scope">
                <el-tag
                  v-if="scope.row.organizationName"
                  type="info"
                  size="small"
                  effect="plain"
                >
                  {{ scope.row.organizationName }}
                </el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="documentCreation"
              label="制单时间"
              min-width="140"
            >
              <template #default="scope">
                {{ formatDateTime(scope.row.documentCreation) }}
              </template>
            </el-table-column>

            <el-table-column label="操作" fixed="right" min-width="150">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="handleEdit(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  link
                  type="danger"
                  size="small"
                  @click="handleDelete(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <!-- 分页 -->
        <el-card shadow="never" class="pagination-card">
          <div class="pagination-container">
            <div class="pagination-info">总{{ page.listCount }}条</div>
            <el-pagination
              v-model:current-page="page.pageindex"
              v-model:page-size="page.pagesize"
              :page-sizes="[10, 20, 50, 100]"
              :total="page.listCount"
              layout="prev, pager, next"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
            <el-select
              v-model="page.pagesize"
              style="width: 100px; margin-left: 10px"
              @change="handleSizeChange"
            >
              <el-option label="10条/页" :value="10" />
              <el-option label="20条/页" :value="20" />
              <el-option label="50条/页" :value="50" />
              <el-option label="100条/页" :value="100" />
            </el-select>
          </div>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox, type TableInstance } from 'element-plus'
import moment from 'moment'
import router from '@/router'
import myaxios from '@/http/MyAxios'

interface InventoryCountItem {
  inventoryCountId: string
  inventoryCountCode: string
  countResult: number
  warehouseId: number
  warehouseName: string
  countTypeId: number
  countTypeName: string
  countStartTime: string
  countEndTime: string
  outboundStatus: number
  inboundStatus: number
  productNames?: string
  countQuantity: number
  gainQuantity: number
  lossQuantity: number
  gainAmount: number
  lossAmount: number
  handlerName: string
  documentCreator: string
  organizationId?: number
  organizationName?: string
  documentCreation: string
}

const loading = ref(false)
const tableData = ref<InventoryCountItem[]>([])
const multipleTableRef = ref<TableInstance>()
const multipleSelection = ref<InventoryCountItem[]>([])

const formInline = reactive({
  inventoryCountCode: '',
  countResult: '',
  countTypeId: '',
  warehouseId: '',
})

const page = reactive({
  pageindex: 1,
  pagesize: 10,
  listCount: 0,
  pageCount: 0,
})

const countTypeOptions = ref<any[]>([])
const warehouseOptions = ref<any[]>([])

const fetchData = async () => {
  loading.value = true
  try {
    const res = await myaxios.get('/api/InventoryCount/GetInventoryCount', {
      params: {
        inventoryCountCode: formInline.inventoryCountCode,
        countResult: formInline.countResult,
        countTypeId: formInline.countTypeId,
        warehouseId: formInline.warehouseId,
        pageindex: page.pageindex,
        pagesize: page.pagesize,
      },
    })
    if (res.data?.success || res.data?.code === 200) {
      const data = res.data.data || {}
      tableData.value = data.data || data.items || []
      page.listCount = data.listCount || data.total || tableData.value.length
      page.pageCount = Math.ceil(page.listCount / page.pagesize)
    }
  } catch (error) {
    console.error('获取盘点数据失败:', error)
    ElMessage.error('获取盘点数据失败')
  } finally {
    loading.value = false
  }
}

const loadCountTypes = async () => {
  try {
    const res = await myaxios.get('/api/InventoryCount/GetCountType')
    if (res.data?.success || res.data?.code === 200) {
      countTypeOptions.value = res.data.data || []
    }
  } catch (error) {
    console.error('获取盘点类型失败:', error)
  }
}

const loadWarehouses = async () => {
  try {
    const res = await myaxios.get('/api/Warehousing/GetWarehouse')
    if (res.data?.success || res.data?.code === 200) {
      warehouseOptions.value = res.data.data || []
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
  }
}

onMounted(() => {
  fetchData()
  loadCountTypes()
  loadWarehouses()
})

const handleQuery = () => {
  page.pageindex = 1
  fetchData()
}

const handleReset = () => {
  formInline.inventoryCountCode = ''
  formInline.countResult = ''
  formInline.countTypeId = ''
  formInline.warehouseId = ''
  page.pageindex = 1
  fetchData()
}

const handleAdvancedSearch = () => {
  ElMessage.info('高级搜索功能待实现')
}

const handleSelectionChange = (val: InventoryCountItem[]) => {
  multipleSelection.value = val
}

const handleCreate = () => {
  router.push({ name: 'CreateInventoryCount' })
}

const handleDetail = (row: InventoryCountItem) => {
  router.push({
    name: 'DetailInventoryCount',
    query: { inventoryCountId: row.inventoryCountId },
  })
}

const handleEdit = (row: InventoryCountItem) => {
  router.push({
    name: 'CreateInventoryCount',
    query: { inventoryCountId: row.inventoryCountId },
  })
}

const handleDelete = (row: InventoryCountItem) => {
  ElMessageBox.confirm('确认删除该盘点单吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const res = await myaxios.delete(
          `/api/InventoryCount/DeleteInventoryCount?inventoryCountId=${row.inventoryCountId}`,
        )
        if (res.data?.success || res.data?.code === 200) {
          ElMessage.success('删除成功')
          fetchData()
        } else {
          ElMessage.error(res.data?.message || '删除失败')
        }
      } catch (error) {
        console.error('删除失败:', error)
        ElMessage.error('删除失败，请稍后重试')
      }
    })
    .catch(() => {})
}

const handleBatchDelete = () => {
  if (!multipleSelection.value.length) {
    ElMessage.warning('请选择需要删除的盘点单')
    return
  }
  ElMessageBox.confirm(
    `确认删除选中的${multipleSelection.value.length}条盘点单吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(async () => {
      const ids = multipleSelection.value
        .map((item) => item.inventoryCountId)
        .join(',')
      try {
        const res = await myaxios.delete(
          `/api/InventoryCount/BatchDeleteInventoryCount?inventoryCountIds=${ids}`,
        )
        if (res.data?.success || res.data?.code === 200) {
          ElMessage.success('批量删除成功')
          fetchData()
        } else {
          ElMessage.error(res.data?.message || '批量删除失败')
        }
      } catch (error) {
        console.error('批量删除失败:', error)
        ElMessage.error('批量删除失败，请稍后重试')
      }
    })
    .catch(() => {})
}

const handleExport = () => {
  ElMessage.info('导出功能待实现')
}

const handleVoid = () => {
  if (!multipleSelection.value.length) {
    ElMessage.warning('请选择需要作废的盘点单')
    return
  }
  ElMessage.info('作废功能待实现')
}

const handleLockWarehouse = () => {
  ElMessage.info('锁定仓库功能待实现')
}

const handleRefresh = () => {
  fetchData()
}

const handleSizeChange = () => {
  page.pageindex = 1
  fetchData()
}

const handleCurrentChange = () => {
  fetchData()
}

const getResultTagType = (result: number) => {
  switch (result) {
    case 0:
      return 'info'
    case 1:
      return 'warning'
    case 2:
      return 'success'
    default:
      return 'info'
  }
}

const getResultText = (result: number) => {
  switch (result) {
    case 0:
      return '草稿'
    case 1:
      return '有盈亏'
    case 2:
      return '无盈亏'
    default:
      return '未知'
  }
}

const getOutboundStatusText = (status: number) => {
  switch (status) {
    case 0:
      return '未出库'
    case 1:
      return '部分出库'
    case 2:
      return '已出库'
    default:
      return '未知'
  }
}

const getInboundStatusText = (status: number) => {
  switch (status) {
    case 0:
      return '未入库'
    case 1:
      return '部分入库'
    case 2:
      return '已入库'
    default:
      return '未知'
  }
}

const formatDate = (date?: string) => {
  if (!date) return ''
  return moment(date).format('YYYY-MM-DD')
}

const formatDateTime = (date?: string) => {
  if (!date) return ''
  return moment(date).format('YYYY-MM-DD HH:mm:ss')
}
</script>

<style scoped>
.inventory-count-page {
  padding: 12px;
}

.toolbar {
  margin-bottom: 16px;
}

.pagination-card {
  margin-top: 16px;
}

.pagination-container {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 10px 0;
}

.pagination-info {
  margin-right: 20px;
  color: #606266;
  font-size: 14px;
}

::deep(.el-pagination) {
  justify-content: flex-end;
}

::deep(.el-pagination .el-pager li) {
  margin: 0 4px;
}

::deep(.el-pagination .el-pager li.is-active) {
  background-color: #67c23a;
  color: #fff;
}
</style>

